package com.zytlifeservice.controller;

import com.zytlifeservice.domain.BaseIcon;
import com.zytlifeservice.domain.Result;
import com.zytlifeservice.exception.UserException;
import com.zytlifeservice.service.BaseIconService;
import com.zytlifeservice.service.FileUploadService;
import com.zytlifeservice.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created by MJS on 2017/5/8.
 */

@RestController
@RequestMapping(value = "/baseIcon")
public class BaseIconController {

    public int[] type_array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,18};

    @Autowired
    BaseIconService baseIconService;
    @Autowired
    FileUploadService fileUploadService;

    /*
    后期做分页处理。
     */
    @GetMapping(value = "/queryAll")
    public Result query(String types) {
        String[] typesStr = types.replaceAll(" ", "").split(",");
        int[] intTypes = new int[typesStr.length];

        try {
            for (int i = 0; i < typesStr.length; i++) {
                intTypes[i] = Integer.parseInt(typesStr[i]);
            }
        } catch (NumberFormatException e) {
            throw new UserException("类型转换错误,请检查格式", 303);
        }

        boolean isInType = true;
        for (int intType : intTypes) {
            if (!contains(intType, type_array)) {
                isInType = false;
                break;
            }
        }
        if (!isInType) {
            throw new UserException("类型错误", 505);
        }
        return ResultUtil.success(baseIconService.queryAll(intTypes), "查询成功");
    }

    private boolean contains(int intType, int[] type_array) {
        for (int i : type_array) {
            if (intType == i) {
                return true;
            }
        }
        return false;
    }

    //添加
    @PostMapping(value = "/add")
    public Result add(String url, String description, int type, @RequestParam("img") MultipartFile[] files) {
        //做好增加和删除。
        boolean isInType = false;
        for (int i : type_array) {
            if (type == i) {
                isInType = true;
                break;
            }
        }
        if (!isInType) {
            throw new UserException("类型错误", 505);
        }

        BaseIcon baseIcon = new BaseIcon();
        String icon;
        System.out.println("length=" + files.length);
        if (files != null && files.length > 0) {
            icon = fileUploadService.storeBaseIcon(files[0]);
        } else {
            icon = "";
        }
        baseIcon.setIcon(icon);
        baseIcon.setDescription(description);
        baseIcon.setType(type);
        baseIcon.setUrl(url);
        baseIconService.add(baseIcon);
        return ResultUtil.success();
    }

    @PostMapping(value = "/delete")
    public Result delete(long id) {
        baseIconService.delete(id);
        return ResultUtil.success();
    }
}
